<template>
    <div class="app-container">
        <!-- 顶部导航栏 -->
        <el-header class="header-container">
            <el-row type="flex" :gutter="5">
                <!--
                <el-col :span="4">
                    <el-label size="mini" style="font-size: 12px;">Source: </el-label>
                    <el-select v-model="selectedSource" placeholder="Select Source" size="mini" clearable>
                        <el-option v-for="source in dict.type.emr_source" :key="source.value" :label="source.label"
                            :value="source.value" />
                    </el-select>
                </el-col>
                -->
                <el-col :span="4">
                    <span size="mini" style="font-size: 12px;" name="status">Status: </span>
                    <el-select v-model="selectedStatus" placeholder="Select Status" size="mini" clearable>
                        <el-option v-for="status in dict.type.status" :key="status.value" :label="status.label"
                            :value="status.value" />
                    </el-select>
                </el-col>
                <el-col :span="18"></el-col>
                <el-col :span="2">
                    <el-button type="primary" size="mini" icon="el-icon-search" @click="randomOneEmr"
                        :loading="nexting">
                        Next
                    </el-button>
                </el-col>
            </el-row>
        </el-header>

        <!-- 主要内容区 -->
        <el-main class="middle-container" style="margin-left: 1px;height:75%; flex:none">
            <el-row :gutter="20">
                <!-- 左侧病历文本区 -->
                <el-col :span="14">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="flex justify-between items-center">
                                <h4> ID:{{ standard.id }}&nbsp;&nbsp;[{{ standard.type }}]</h4>
                                <div>
                                    <el-button type="text" size="medium" icon="el-icon-printer" @click="printRecord"
                                        title="print" />
                                    <el-button type="text" size="medium" icon="el-icon-document-copy"
                                        @click="copyRecord" title="copy" />
                                    <el-button type="text" size="medium" icon="el-icon-edit" @click="handleUpdate"
                                        title="edit" />
                                </div>
                            </div>
                        </template>

                        <div class="record-content">
                            <div class="patient-info">
                                <el-row :gutter="20">
                                    <el-col :span="8"><span class="info-label" size="mini">Date:</span><span
                                            style="font-size: 15px;">{{
                                                standard.year
                                            }}-{{
                                                standard.month }}</span></el-col>
                                    <el-col :span="8"><span class="info-label">Source:</span><span
                                            style="font-size: 15px;">{{ standard.source
                                            }}</span></el-col>
                                    <el-col :span="8"><span class="info-label">Status:</span>
                                        <div v-for="status in dict.type.status" :key="status.value"
                                            style="display: inline-block;font-size: 15px;">
                                            <span v-if="status.value === standard.status" class="status-label"
                                                :style="{ backgroundColor: getColor(standard.status) }">
                                                {{ status.label }}
                                            </span>
                                        </div>
                                    </el-col>
                                </el-row>
                            </div>

                            <div class="record-details mt-4">
                                <div v-html="emrContent" style="font-size: 15px;"></div>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 右侧JSON编辑区 -->
                <el-col :span="10">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="flex justify-between items-center">
                                <h4>Annotated results：</h4>

                                <div>
                                    <el-select v-model="adeService.config.llmModel" placeholder="Select LLM" size="mini"
                                        clearable style="margin-right: 10px;width:150px">
                                        <el-option v-for="dict in dict.type.llm_model" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                    <el-select v-model="adeService.config.promptType" placeholder="Select Prompt"
                                        size="mini" clearable style="margin-right: 10px;width:100px">
                                        <el-option v-for="dict in dict.type.prompt_type" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                    <el-button type="primary" size="mini" icon="el-icon-search" @click="recognizeADE"
                                        :loading="recognizing">ADE Recognition</el-button>
                                </div>


                                <div>
                                    <el-button type="text" size="medium" icon="el-icon-refresh" @click="resetJson"
                                        title="reset" />
                                    <el-button type="text" size="medium" icon="el-icon-warning-outline"
                                        @click="formatJson" title="format" />
                                    <el-button type="text" size="medium" icon="el-icon-check" @click="validateJson"
                                        title="validate" />
                                </div>


                            </div>
                        </template>

                        <div class="json-editor-container">
                            <el-input type="textarea" v-model="jsonText" :rows="22" style="font-size: 14px;"
                                placeholder="Pls input json data(ades)" @input="onJsonChange" />

                            <div class="json-status mt-2">
                                <el-tag :type="jsonValid ? 'success' : 'danger'" effect="plain" size="mini">
                                    {{ jsonStatusText }}
                                </el-tag>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-main>

        <!-- 底部操作区 -->
        <el-footer class="footer-container">
            <el-row type="flex" justify="end">
                <el-button type="warning" class="ml-3" @click="saveRecord('2')" :loading="saving">
                    Not Sure
                </el-button>
                <el-button type="primary" class="ml-3" @click="saveRecord('0')" :loading="saving">
                    UnChecked
                </el-button>
                <el-button type="success" class="ml-3" @click="saveRecord('1')" :loading="saving">
                    Checked
                </el-button>
            </el-row>
        </el-footer>



        <!-- 添加或修改标准数据集对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body style="margin-bottom: 5px;">
            <el-form ref="form">
                <el-form-item label="Content" prop="content">
                    <el-input v-model="standard.content" :rows="14" type="textarea" placeholder=""
                        style="font-size: 15px;" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">OK</el-button>
                <el-button @click="cancel">Cancel</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { recognize } from "@/api/ade/adeRecognition";
import { randomEmr, updateEmr, getEmr } from "@/api/ade/emr";

export default {
    name: 'EmrRecordEditor',
    dicts: ['status', 'llm_model', 'prompt_type'],
    data() {
        return {
            // 表单数据
            selectedStatus: '0',   //non-checked

            //ade服务相关数据
            adeService: {
                emr: '',
                config: {
                    llmModel: 'ernie-3.5-8k',
                    promptType: 'SAG',
                    afterFilter: true,  // 是否进行后处理过滤
                },
            },

            // 病历数据
            standard: {
                id: '',
                year: '',
                month: '',
                source: '',
                status: '',
                type: '',
                content: '',
                ades: '' // JSON格式的ADEs数据
            },
            //emr内容
            emrContent: '',   //带有标签的EMR内容


            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,

            // JSON数据
            jsonText: '',
            jsonValid: true,
            jsonStatusText: 'JSON Format Correct',

            // 状态
            loading: false,
            nexting: false,
            saving: false,
            recognizing: false,
        };
    },
    computed: {

    },
    created() {
        // 初始化JSON文本
        // this.resetJson();
        this.randomOneEmr();
    },
    methods: {

        //==========================================================ADE识别相关操作========================================================

        recognizeADE() {
            this.recognizing = true;
            this.adeService.emr = this.standard.content;  //获取当前要分析的病程记录
            recognize(this.adeService).then(response => {

                this.jsonText = JSON.stringify(response.data.ades, null, 2);
                this.validateJson(); // 验证JSON格式


                // 格式化EMR内容，突出显示识别出的ADE
                let rep = '';
                this.emrContent = this.standard.content; // 初始化格式化的EMR内容
                for (let i = 0; i < response.data.ades.length; i++) {
                    rep = response.data.ades[i].sentence; // 将其他ADE名称用 | 分隔
                    this.emrContent = this.emrContent.replaceAll(rep, '<font color="red">' + rep + '</font>');
                }
                this.recognizing = false;
            }).catch(error => {
                console.error('Error recognizing ADE:', error);
                this.$message.error('Failed to recognize ADE');
                this.recognizing = false;
                this.jsonText = '';
            });
        },


        //==========================================================编辑病例内容========================================================
        cancel() {
            this.open = false;
            this.title = "";
        },
        submitForm() {
            //更新EMR内容
            var data = {
                id: this.standard.id,
                content: this.standard.content
            };
            updateEmr(data).then(response => {
                this.$modal.msgSuccess("Edit Successfully");
                this.open = false;
                this.getCurrentStandard();
            }).catch(error => {
                this.$modal.msgError(`Fail: ${error.message}`);
            });
        },
        /** 修改按钮操作 */
        handleUpdate() {
            this.open = true;
            this.title = "Edit";
        },

        getColor(value) {
            switch (value) {
                case '0':
                    return 'red';
                case '1':
                    return 'green';
                case '2':
                    return 'gray';
                default:
                    return 'yellow'; // 默认颜色
            }
        },

        //==========================================================重新获取当前EMR========================================================
        getCurrentEmr() {
            this.nexting = true;
            getEmr(this.standard.id).then(response => {
                if (response.data == null || response.data == undefined) {
                    this.$message.warning('No aviliable emr data, please change the source or status!');
                    this.nexting = false;
                    return;
                }
                this.standard = response.data;
                let rep = '';
                this.emrContent = this.standard.content; // 初始化格式化的EMR内容
                if (this.standard.ades.length > 2) {
                    const parsed = JSON.parse(this.standard.ades);
                    for (let i = 0; i < parsed.length; i++) {
                        rep = parsed[i].sentence; // 将其他ADE名称用 | 分隔
                        this.emrContent = this.emrContent.replaceAll(rep, '<font color="red">' + rep + '</font>');
                    }
                }

                this.jsonText = this.standard.ades;
                this.formatJson();
                this.nexting = false;
            }).catch(error => {
                this.$message.error(`Fail: ${error.message}`);
                this.nexting = false;
            });
        },
        // 随机病历
        randomOneEmr() {
            this.nexting = true;
            var data = { status: this.selectedStatus }
            randomEmr(data).then(response => {
                if (response.data == null || response.data == undefined) {
                    this.$message.warning('No aviliable emr data, please change the source or status!');
                    this.nexting = false;
                    return;
                }
                this.standard = response.data;
                console.log('randomOneEmr response:', this.standard);
                let rep = '';
                this.emrContent = this.standard.content; // 初始化格式化的EMR内容
                if (this.standard.ades == null || this.standard.ades == undefined) {
                    this.standard.ades = '[]'; // 如果没有ADEs数据，初始化为空数组
                } else {
                    if (this.standard.ades.length > 2) {
                        const parsed = JSON.parse(this.standard.ades);
                        for (let i = 0; i < parsed.length; i++) {
                            rep = parsed[i].sentence; // 将其他ADE名称用 | 分隔
                            this.emrContent = this.emrContent.replaceAll(rep, '<font color="red">' + rep + '</font>');
                        }
                    }
                }
                this.jsonText = this.standard.ades;
                this.formatJson();
                this.nexting = false;
            }).catch(error => {
                // this.$message.error("Too fast, please wait a moment!");
                this.nexting = false;
            });
        },


        //=====================================================JSON编辑器相关操作========================================================
        // 重置JSON数据
        resetJson() {
            this.jsonText = this.standard.ades;
            this.jsonValid = true;
            this.jsonStatusText = 'JSON Format Correct!';
        },
        // 格式化JSON
        formatJson() {
            try {
                const parsed = JSON.parse(this.jsonText);
                this.jsonText = JSON.stringify(parsed, null, 2);
                this.jsonValid = true;
                this.jsonStatusText = 'JSON Format Correct!';
            } catch (error) {
                this.jsonValid = false;
                this.jsonStatusText = `Wrong Format: ${error.message}`;
                this.$message.error('JSON Format Wrong，Can not be formatted!');
            }
        },
        // 验证JSON
        validateJson() {
            try {
                JSON.parse(this.jsonText);
                this.jsonValid = true;
                this.jsonStatusText = 'JSON Foramat Correct';
                // this.$message.success('JSON格式验证通过');
            } catch (error) {
                this.jsonValid = false;
                this.jsonStatusText = `Wrong Format: ${error.message}`;
                this.$message.error('Wrong JSON Format, please fix it first!');
            }
        },

        // JSON内容变化时自动验证
        onJsonChange() {
            try {
                JSON.parse(this.jsonText);
                this.jsonValid = true;
                this.jsonStatusText = 'JSON Format Correct';
            } catch (error) {
                this.jsonValid = false;
                this.jsonStatusText = `Wrong Format: ${error.message}`;
            }
        },


        //=====================================================ADE 语料审核处理========================================================
        //标记不确定的病历
        saveRecord(cur_status) {
            this.validateJson();
            if (!this.jsonValid) {
                this.$message.error('JSON Format Wrong, please fix it first!');
                return;
            }

            this.saving = true;
            var data = {
                id: this.standard.id,
                status: cur_status,
                ades: this.jsonText
            };
            console.log('saveRecord data:', data);
            updateEmr(data).then(response => {
                this.saving = false;
                this.$message.success('Successfully marked as Not Sure');
                this.getCurrentEmr();
            }).catch(error => {
                this.saving = false;
                this.$message.error(`Fail: ${error.message}`);
            });


        },

        // 打印病历
        printRecord() {
            window.print();
        },

        // 复制病历
        copyRecord() {
            const textToCopy = this.standard.content;

            navigator.clipboard.writeText(textToCopy)
                .then(() => {
                    this.$message.success('Copy successful!');
                })
                .catch(err => {
                    this.$message.error('Copy failed: ' + err);
                    console.error('Copy failed:', err);
                });
        },

    }
}
</script>

<style>
/* 全局样式 */
.app-container {
    display: flex;
    flex-direction: column;
}

.header-container {
    height: 35px !important;
    padding: 0 10px;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
}

.middle-container {
    padding: 10px;
}

.footer-container {
    height: 70px !important;
    padding: 0 20px;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

/* 病历内容样式 */
.record-content {
    padding: 10px;
}

.patient-info {
    margin-bottom: 10px;
}

.info-label {
    font-weight: 500;
    font-size: 14px;
    color: #606266;
    margin-right: 5px;
}

/* JSON编辑器样式 */
.json-editor-container {
    position: relative;
}

.json-status {
    text-align: right;
}

/* 自定义Element组件样式 */
.el-card__header {
    font-weight: 500;
    color: #303133;
}

.el-descriptions-item__label {
    background-color: #f5f7fa;
}

.status-label {
    color: white;
    /* 文字颜色 */
    padding: 1px 1px;
    border-radius: 2px;
    display: inline-block;
    margin: 1px;
}
</style>